/*
 * TODO: Enter copyright statement here.
 */
package com.googlecode.wcbunittests.helloworld.element;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.Calendar;
import java.util.logging.Logger;

import nl.gx.webmanager.springmvc.controller.component.ElementComponentController;

import org.springframework.beans.BeanUtils;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;

import com.googlecode.wcbunittests.helloworld.api.HelloWorldElement;
import com.googlecode.wcbunittests.helloworld.api.RBACConstants;
import com.googlecode.wcbunittests.helloworld.element.validator.PastDateValidator;
import com.googlecode.wcbunittests.helloworld.propertyeditor.CalendarPropertyEditor;

/**
 * Controller for the HelloWorld element.
 */
public class HelloWorldElementController extends ElementComponentController {
    // Static logger for the class
    private static final Logger LOG = Logger.getLogger(HelloWorldElementController.class.getName());

    // Properties that will be ignored when copying bean properties using BeanUtils
    private static final String[] BEANUTILS_COPYPROPERTIES_IGNORE = {"presentation"};

    // Private member variable to store the form backing object, making it stateful during the lifetime
    // of one HTTP request. Note that the HelloWorld element controller is not stateful itself so a new
    // instance of the controller and form backing object will be created for each HTTP request.
    private HelloWorldElementFBO myFormBackingObject;

    // Validator for past date
    private PastDateValidator myValidator = null;

    /**
     * {@inheritDoc}
     */
    @Override
    public Object formBackingObject(HttpServletRequest request) throws ServletException {
        if (myFormBackingObject == null) {
            // Create Form Backing Object
            myFormBackingObject = new HelloWorldElementFBO(this);

            // Initialize form backing object with element values
            HelloWorldElement element = (HelloWorldElement) getElement();

            // Initialize form backing object with default values from element,
            // use BeanUtils of the Spring framework for this purpose
            BeanUtils.copyProperties(element, myFormBackingObject, BEANUTILS_COPYPROPERTIES_IGNORE);
        }

        // Return the Form Backing Object
        return myFormBackingObject;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void initBinder(HttpServletRequest request, org.springframework.web.bind.ServletRequestDataBinder binder)
    throws Exception {
       super.initBinder(request, binder);

        // Add a date validator to only accept dates in the past
        if (myValidator == null) {
            myValidator = new PastDateValidator();
            addValidator(myValidator);
        }

        // Register a date editor for the date property to accept the syntax MM/dd/yyyy,
        // which is the default of our calendar property editor
        binder.registerCustomEditor(Calendar.class, new CalendarPropertyEditor());
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
                    BindException errors, ModelAndView modelAndView) throws Exception {
        if (((HelloWorldElementComponent) getComponent()).getAuthorizationService()
                .checkAccess(RBACConstants.UPDATE_ELEMENT)) {
            // Copy properties from the FBO to the business object
            HelloWorldElement element = (HelloWorldElement) getElement();

            // Update HelloWorld element impl with these values
            if (element != null) {
                // Update the HelloWorld element with values from the form backing
                // object, use BeanUtils of the Spring framework for this purpose
                BeanUtils.copyProperties(myFormBackingObject, element);
            }
        } else {
            LOG.warning("No authorization to update HelloWorld elements");
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void createEditViews() {
        super.createEditViews();
        addEditView("editHelloWorldElement.jspf", "");
    }
}